﻿using System.Security.Cryptography;
using System.Text;

namespace ScreenWarnning.Helpers
{
    internal class DesHelper
    {
        // <summary> 
        /// AES解密 
        /// </summary> 
        /// <param name="input">密文字节数组</param> 
        /// <param name="key">密钥（16位）</param> 
        /// <returns>返回解密后的字符串</returns> 
        public static string DecryptByDES(string input, string key = "HHHTwqb#@!2021")
        {
            byte[] inputBytes = Convert.FromBase64String(input);
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            using (DESCryptoServiceProvider aesAlg = new DESCryptoServiceProvider())
            {
                aesAlg.Padding = PaddingMode.PKCS7;
                aesAlg.Mode = CipherMode.ECB;
                aesAlg.Key = keyBytes;
                aesAlg.IV = keyBytes;
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srEncrypt = new StreamReader(csEncrypt))
                        {
                            return srEncrypt.ReadToEnd();
                        }
                    }
                }
            }
        }

        /// <summary> 
        /// AES加密算法 
        /// </summary> 
        /// <param name="input">明文字符串</param> 
        /// <param name="key">密钥（16位）</param> 
        /// <returns>字符串</returns> 
        public static string EncryptByDES(string input, string key= "HHHTwqb#@!2021")
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            using (DESCryptoServiceProvider aesAlg = new DESCryptoServiceProvider())
            {
                aesAlg.Padding = PaddingMode.PKCS7;
                aesAlg.Mode = CipherMode.ECB;
                aesAlg.Key = keyBytes;
                aesAlg.IV = keyBytes;
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(input);
                        }
                        byte[] bytes = msEncrypt.ToArray();
                        var ddc = Convert.ToBase64String(bytes);

                        byte[] inputBytes = Convert.FromBase64String(ddc);
                        return ddc;
                    }
                }
            }
        }
    }
}
